package com.ld.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//处理整个web的controller异常
//@ControllerAdvice
public class GlobalExceptionController {
    /**
     Controller的返回值通常只有2种：
     1,返回视图. 2,返回数据(通常是JSON).
     判断的依据是有没有加@ResponseBody.加了就是返回数据,没加就是返回视图
     */
    /**
     * @param request       请求对象
     * @param response      响应对象
     * @param handlerMethod 发生异常的方法对象
     * @param e             异常对象
     * @return
     */
   // @ExceptionHandler({Exception.class})
    public Object name(HttpServletRequest request, HttpServletResponse response,
                       HandlerMethod handlerMethod, Exception e) {
        System.out.println(handlerMethod instanceof HandlerMethod);
        System.out.println("isAjax=" + isAjax(request));
        if (!isAjax(request)) {//不是ajax
            //默认的异常处理,返回到视图/error/exception.html
            ModelAndView mv = new ModelAndView("/error/exception");
            mv.addObject("Exception", e);
            return e;
        }
        return "你妈逼";
    }

    /**
     * 判断网络请求是否为ajax
     *
     * @param req
     * @return 请求时ajax时返回true
     */
    private boolean isAjax(HttpServletRequest req) {
        String contentTypeHeader = req.getHeader("Content-Type");
        String acceptHeader = req.getHeader("Accept");
        String xRequestedWith = req.getHeader("X-Requested-With");
        return (contentTypeHeader != null && contentTypeHeader.contains("application/json"))
                || (acceptHeader != null && acceptHeader.contains("application/json"))
                || "XMLHttpRequest".equalsIgnoreCase(xRequestedWith);
    }

}
